package com.gitee.wsl.ext.list

internal fun <T> MutableList<T>.withAll(iterator: Iterator<T>): MutableList<T> {
    while (iterator.hasNext()) {
        add(iterator.next())
    }
    return this
}

internal fun<T> MutableList<T>.withMore(next: T): MutableList<T> {
    add(next)
    return this
}

fun <T> List<T>.interleaveWith(other: List<T>): List<T> {
    tailrec fun rec(l1: Iterator<T>, l2: Iterator<T>, acc: MutableList<T>): List<T> =
        when {
            !l1.hasNext() && !l2.hasNext() -> acc
            l1.hasNext() && !l2.hasNext() -> acc.withAll(l1)
            !l1.hasNext() && l2.hasNext() -> acc.withAll(l2)
            else -> rec(l1, l2, acc.withMore(l1.next()).withMore(l2.next()))
        }
    return rec(this.iterator(), other.iterator(), mutableListOf())
}


